package practise.leetcode.q17;

import java.util.*;

public class Solution {
    private Map<String, List<String>> digitsCharaters = new HashMap<>(8);

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.isEmpty()) {
            return Collections.emptyList();
        }

        init();
        List<String> strings = null;
        for (int i = 0; i < digits.length(); i++) {
            String digit = String.valueOf(digits.charAt(i));
            strings = letterCombinations(digit, strings);
        }
        return strings;
    }

    private List<String> letterCombinations(String digit, List<String> strings) {
        List<String> charaters = digitsCharaters.get(digit);        
        if (strings == null) {
            return charaters;
        }

        List<String> results = new ArrayList<>(charaters.size() * strings.size());
        for (String s : strings) {
            for (String character : charaters) {
                results.add(s + character);
            }
        }
        return results;
    }

    private void init() {
        digitsCharaters.put("2", Arrays.asList("a", "b", "c"));
        digitsCharaters.put("3", Arrays.asList("d", "e", "f"));
        digitsCharaters.put("4", Arrays.asList("g", "h", "i"));
        digitsCharaters.put("5", Arrays.asList("j", "k", "l"));
        digitsCharaters.put("6", Arrays.asList("m", "n", "o"));
        digitsCharaters.put("7", Arrays.asList("p", "r", "q", "s"));
        digitsCharaters.put("8", Arrays.asList("t", "u", "v"));
        digitsCharaters.put("9", Arrays.asList("w", "x", "y", "z"));
    }
}
